//
//  Compressor.swift
//  live
//
//  Created by melvyn on 2018/9/4.
//  Copyright © 2018 NEET. All rights reserved.
//

import UIKit

func ImageJPEGRepresentation(_ image: UIImage, _ compressionQuality: CGFloat) -> Data? {
    
    var size = image.size
    let boundary: CGFloat = 1280
    
    if size.width > boundary && size.height > boundary {
        let identity = max(size.width, size.height) / min(size.width, size.height)
        if identity <= 2 {
            let factor = max(size.width, size.height) / boundary
            if size.width > size.height {
                size.width = boundary
                size.height = size.height / factor
            } else {
                size.height = boundary
                size.width = size.width / factor
            }
        } else {
            if min(size.width, size.height) >= boundary {
                let factor = min(size.width, size.height) / boundary
                if size.width < size.height {
                    size.width = boundary
                    size.height = size.height / factor
                } else {
                    size.height = boundary
                    size.width = size.width / factor
                }
            }
        }
    }
    
    let bounds = CGRect.init(origin: .zero, size: size)
    var newImage: UIImage!
    UIGraphicsBeginImageContext(bounds.size)
    newImage = UIImage(cgImage: image.cgImage!, scale: 1, orientation: image.imageOrientation)
    newImage.draw(in: bounds)
    newImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    
    return newImage.jpegData(compressionQuality: compressionQuality)
}
